package com.ecloud.trend.utils;

import TrendDB.API;
import TrendDB.DB_Exception;

/**
 * trenddb.addr=10.89.20.20:9000
 * trenddb.userName=admin
 * trenddb.password=123456
 * trenddb.database=xtmp
 *
 * @author Squbirreland
 */
public class TrendConnFactory {

    private TrendConnFactory() {
    }

    private static String[] servers = {};

    private static int connId = -1;


    private static String[] initServers() {
        String[] servers = {};
        try {
            API.StartupAPI();
            String[] address = {"10.89.20.20:9000"};
            API.InitNameServers(address);
            servers = API.ListServers();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return servers;
    }

    private static int createConn() {
        try {
            return API.CreateConnection("xtmp" + "@" + servers[0], false, true, "admin", "123456");
        } catch (DB_Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 获取链接ID 如果未初始化 则初始化
     * 如果链接失效 则重新创建
     *
     * @return connId
     * @author Squbi
     * @date 2021/6/28 15:58
     */
    public static int getConn() {
        if (servers == null || servers.length == 0) {
            servers = initServers();
        }
        try {
            if (connId == -1 || 0 != API.TestServer(connId)) {
                connId = createConn();
            }
        } catch (DB_Exception e) {
            e.printStackTrace();
            connId = createConn();
        }
        return connId;
    }
}
